import * as api from '@/services/checkTask';
import { DrawerForm, ProFormInstance } from '@ant-design/pro-form';
import { Button, Checkbox, Col, Divider, Row, Tag, message } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import * as utils from '@/utils/utils';
import { ProFormSelect, ProFormText } from '@ant-design/pro-components';
import * as c from '@/services/consts';
import CheckServer from '@/components/CheckServer';

type VpnServerFormProps = {
  visible: boolean;
  currentTask: API.CheckTask | undefined;
  customs?: string[];
  onCancel: () => void;
  onSubmit: () => void;
};

const VpnServerForm: React.FC<VpnServerFormProps> = (props) => {
  const { visible, onCancel, onSubmit, customs, currentTask } =
    props;

  if (!visible || !currentTask) {
    return null;
  }

  const [myloading, setMyloading] = useState<boolean>(true);
  const [checkedList, setCheckedList] = useState<any[]>(currentTask.serverIds ?? []);
  const [checkedDomainList, setCheckedDomainList] = useState<any[]>(customs ?? (currentTask.customs ?? []));  
  const [dataDomains, setDataDomains] = useState<API.CheckDomainModel[] | undefined>(undefined);

  const formRef = useRef<ProFormInstance>();

  const loadData = async () => {
    const resultDomains = await api.domainlist();
    if (resultDomains && resultDomains.data) {
      setDataDomains(resultDomains.data);
    } else {
      setDataDomains([]);
    }

    setMyloading(false);
  };

  useEffect(() => {
    loadData();
  }, []);

  const handleSubmit = async (record: API.CheckTask) => {
    console.log(checkedList,checkedDomainList);
    if(!checkedList || checkedList.length == 0){
      message.error("请选择用于检测的服务器");
      return;
    }
    if(!checkedDomainList || checkedDomainList.length == 0){
      message.error("请选择检测的域名");
      return;
    }
    
    let data = {
      recheckId: currentTask.id,
      serverIds: checkedList,
      customs: checkedDomainList,
      job: c.CheckJob.CheckApi.value,
      level: record.level,
    };
    const result = await api.create(data);
    if (result && result.success) {
      onSubmit();
    }
  };

  return (
    <DrawerForm<API.CheckTask>
      open={visible}
      title={
        <>
          域名检测
        </>
      }
      formRef={formRef}
      autoFocusFirstInput
      width={1224}
      onFinish={handleSubmit}
      loading={myloading}
      drawerProps={{
        // forceRender: true,
        // destroyOnClose: true,
        // closable: false,
        onClose: onCancel,
        maskClosable: false,
      }}
      initialValues={currentTask}
    >
    <Row gutter={24} style={{marginTop:10}}>
      <Col span={4}>
        <ProFormSelect
          name='level'
          label="任务等级"
          allowClear={false}
          options={c.CheckLevelOptions}
          mode='single'
          initialValue={c.CheckLevel.Normal.value}
          rules={[{ required: true, message: '请选择任务等级' }]}
        />
      </Col>
    </Row>

    <Row>
      <Col span={24} style={{marginBottom:-20}}>
        <ProFormText
          name="name"
          label="自定义名称"
        />
      </Col>
    </Row>
    
    <Divider orientation="left" orientationMargin={0}>检测服务器</Divider>
      <CheckServer onChange={setCheckedList} width={1100} initValues={checkedList} />
      
      <Checkbox.Group key="ckgDomains" onChange={setCheckedDomainList} value={checkedDomainList}>
        <Row gutter={24} style={{width:1100}}>
        <Col span={24} style={{minWidth:1100}}>

        {dataDomains?.map((gc) => {
          return <><Row gutter={24}><Col span={24} style={{marginTop:20}}>
            <Divider orientation="left" orientationMargin={0} style={{marginBottom:20}}>{gc.type} 
            <Button
              type='primary'
              ghost
              key="check_all"
              onClick={() => {
                let domains = gc.domains?.map((val)=>val.domain) ?? [];
                // console.log(domains);
                setCheckedDomainList(Array.from(new Set(domains.concat(checkedDomainList))))
              }}
              style={{marginLeft:10}}
            >
              全选
            </Button>
            </Divider>
            </Col></Row>
          <Row gutter={24}>{
            gc.domains?.map((dm)=>{
            return (<Col span={8}>
              <Checkbox value={dm.domain} style={{ verticalAlign: 'middle' }}>
                <Tag color={utils.getTextRanColor(dm.type)}>{dm.type}</Tag>{dm.domain}
              </Checkbox></Col>
            );
          })}</Row></>
        })}

        </Col>
        </Row>
      </Checkbox.Group>


    </DrawerForm>
  );
};

export default VpnServerForm;
